package com.zrb.mobile;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;

 
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.loopj.android.http.AsyncHttpResponseHandler;
 
 
import com.zrb.mobile.XList.IXListViewRefreshListener;
import com.zrb.mobile.XList.XListView;
import com.zrb.mobile.adapter.News_tablistItemAdapter;
 
import com.zrb.mobile.adapter.News_tablistItemAdapter.OnFavoriteListener;
import com.zrb.mobile.adapter.model.NewsDto;
import com.zrb.mobile.adapter.model.NewsDtos;
 
import com.zrb.mobile.common.NewsCache;
 
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.register.User_phone_login;
import com.zrb.mobile.ui.onLoadMoreListener;
import com.zrb.mobile.utility.CollectionHelper;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.ZrbRestClient;
 
 

@SuppressLint("ValidFragment")
public class News_tablist_Fragment extends BaseLazyFragment implements IXListViewRefreshListener,  OnFavoriteListener, onLoadMoreListener
{
	private static final int LOAD_MORE = 0x110;
	private static final int LOAD_REFREASH = 0x111;

	private static final int TIP_ERROR_NO_NETWORK = 0X112;
	private static final int TIP_ERROR_SERVER = 0X113;
 
	private boolean isFirstIn = true;
	CollectionHelper mCollectionHelper;
	/**
	 * ��ǰ����Ƿ��Ǵ������л�ȡ��
	 */
	private boolean isLoadingDataFromNetWork;

	/**
	 * Ĭ�ϵ�newType
	 */
	private int newsType = -1;//Constaint.NEWS_TYPE_YEJIE;
	/**
	 * ��ǰҳ��
	 */
	private int currentPage = 1;
	/**
	 * �������ŵ�ҵ����
	 */
	//private NewsItemBiz mNewsItemBiz;

	/**
	 * ����ݿ⽻��
	 */
	//private NewsItemDao mNewsItemDao;

	/**
	 * ��չ��ListView
	 */
	private XListView mXListView;
	/**
	 * ���������
	 */
	private News_tablistItemAdapter mAdapter;

	/**
	 * ���
	 */
	private List<NewsDto> mDatas = new ArrayList<NewsDto>();
	private Activity mactivity;
	
	//private Handler mhandler=new Handler();
	//Toast��ʾ��
	private RelativeLayout notify_view;
	private TextView notify_view_text;
	public final static int SET_NEWSLIST = 0;
 	
	@Override
	 public  void onCreate(Bundle savedInstanceState)
     {
        super.onCreate(savedInstanceState);
        if ((savedInstanceState != null) && savedInstanceState.containsKey("newsType")) {
        	newsType = savedInstanceState.getInt("newsType");
        }
        //mNewsItemBiz = new NewsItemBiz();
     }
	
	@Override
	 public  void onSaveInstanceState(Bundle outState)
     {
         CommonUtil.InfoLog("News_tablist_Fragment", "start");
         super.onSaveInstanceState(outState);
         outState.putInt("newsType", newsType);
     }
 	
	public static final News_tablist_Fragment newInstance(int newsType) {
		News_tablist_Fragment fragment = new News_tablist_Fragment();
		fragment.newsType=newsType;
		return fragment;
	}
 
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		this.mactivity = activity;
		super.onAttach(activity);
	}
	
	Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case SET_NEWSLIST:
				 
				if(mAdapter == null){
 			    	mAdapter = new News_tablistItemAdapter(getActivity(), mDatas);
					mAdapter.setImgLoader(imageLoader);
					mXListView.setAdapter(mAdapter);
					firstLoad();
				}
				else
				{
					//isFirstIn=true;
					mXListView.setAdapter(mAdapter);
					firstLoad();
				}
			
 			break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	
	
	/** �˷�����˼Ϊfragment�Ƿ�ɼ� ,�ɼ�ʱ�������� */
	/*@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		if (isVisibleToUser) {
			//fragment�ɼ�ʱ�������
			if(mDatas !=null && mDatas.size() !=0){
				mhandler.obtainMessage(SET_NEWSLIST).sendToTarget();
			}else{
				new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							Thread.sleep(2);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mhandler.obtainMessage(SET_NEWSLIST).sendToTarget();
					}
				}).start();
			}
		}else{
			//fragment���ɼ�ʱ��ִ�в���
		}
		super.setUserVisibleHint(isVisibleToUser);
	}*/
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view= inflater.inflate(R.layout.news_tab_item_fragment, null);
 		//Toast��ʾ��
		notify_view = (RelativeLayout)view.findViewById(R.id.notify_view);
		notify_view_text = (TextView)view.findViewById(R.id.notify_view_text);
	 	
		mXListView = (XListView) view.findViewById(R.id.id_xlistView);
		mXListView.setPullRefreshEnable(this);
		mXListView.setOnLoadMoreListener(this);
		//mXListView.setPullLoadEnable(this);
		mXListView.setRefreshTime(CommonUtil.getRefreashTime(getActivity(), newsType));
 		// mXListView.NotRefreshAtBegin();

		mXListView.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				Intent intent = new Intent(getActivity(), News_WebContentActivity.class);
				NewsDto tmpDto=mAdapter.getCurItem(position-1);
				intent.putExtra("title", tmpDto.title);
				intent.putExtra("newid",tmpDto.id);
				startActivity(intent);
			}

		});
		return view;
	}

	private void show() {
	 	if (!mXListView.isStackFromBottom()) {
			mXListView.setStackFromBottom(true);
		} 
		mXListView.setStackFromBottom(false);
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		//mNewsItemDao = new NewsItemDao(getActivity());
	 		
/*		mAdapter = new News_tablistItemAdapter(getActivity(), mDatas);
		mAdapter.setImgLoader(imageLoader);*/
		mAdapter = new News_tablistItemAdapter(getActivity(), mDatas);
		mAdapter.setOnFavoriteListener(this);
		mAdapter.setNewType(this.newsType);
		mAdapter.setImgLoader(imageLoader);
		mXListView.setAdapter(mAdapter);
		//firstLoad();
 	}

 
	
	@Override 
	public void onResume()
	{
		super.onResume();
		//if (this.getUserVisibleHint()) firstLoad();
 	}
	
	@Override 
	public void onFirstUserVisible() {
		firstLoad();
    }
	
	private void firstLoad()
	{
		if (isFirstIn){
 			isFirstIn = false;
			mXListView.startRefresh();
		} 
		else {
			mXListView.NotRefreshAtBegin();
		}
 	}
	
	public void notifyRefresh(){
 		isFirstIn=true;
 		mXListView.update();
 		//mXListView.scrollTo(0, 0);  
		//firstLoad();
 		onRefresh();
  	}
	
	@Override
	public void onRefresh()
	{
  		currentPage=1;
		//LoadDate(mAdapter.getMaxId(),true,10);
		mhandler.postDelayed(new Runnable(){
	 		   @Override
				public void run() {
 	 			   LoadDate("",false,10);
				}
	    }, 1000);
 	}

	@Override
	public void OnLoadMoreEvent() {
		// TODO Auto-generated method stub
		currentPage++;
		mhandler.postDelayed(new Runnable(){
            @Override
           public void run() {
            	LoadDate(mAdapter.getMinId()+"",false,10);
           }
        }, 300);
 	}
	
	public void onLoadMore()
	{
		currentPage++;
		LoadDate(mAdapter.getMinId()+"",false,10);
	}
 	
	private void LoadDate(String idx,final boolean isforward,int pagesize)
	{
     	String url=String.format("news/query?id=%1$s&forward=%2$b&limit=%3$d", idx,isforward,pagesize);
 		if(newsType!=-1) url+="&category="+newsType;
		ZrbRestClient.get(url, null,  new AsyncHttpResponseHandler()
    	{
  			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				//loadingview.HideText("������ݳ��?").ShowRefleshBtn(true).ShowError();
 				initNotify(-1,News_tablist_Fragment.this.getString(R.string.error_net_loadfail));
 				handerError();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
 				String results=new String(arg2);
				try {
					GsonBuilder gsonb = new GsonBuilder();  
			        Gson gson = gsonb.create();  
			        NewsDtos tmpDto=	gson.fromJson(results, NewsDtos.class);
			        if(tmpDto.res==1){
 			        	 if(currentPage==1) {
 					        	NewsCache.saveRecentNews(newsType, results);
		 			        	mAdapter.setDatas(tmpDto.data);
		 			        	mXListView.stopRefresh();
					        	initNotify(tmpDto.data.size(),"");
 					      }
		 			      else{
		 			        	mXListView.hideloading();
					        	mAdapter.addAll(tmpDto.data);
		 			      }
						  mAdapter.notifyDataSetChanged();
			        }
			        else{
			        	initNotify(-1,tmpDto.msg);
			        	handerError();
			        }
    			}
				catch(Exception e){
 				   //loadingview.HideText(e.getMessage()).ShowRefleshBtn(true).ShowError();
					System.out.println("eeee!!!!"+e.getMessage());
 				}
				CommonUtil.setRefreashTime(getActivity(), newsType);
				// ����ˢ��ʱ��
				//mXListView.setRefreshTime(CommonUtil.getRefreashTime(getActivity(), newsType));
		
				//mXListView.stopLoadMore();
 			}});
 	}
	
	private void handerError(){
		if(currentPage==1)  {
 			mXListView.stopRefresh();
		    if(mAdapter.isEmpty()){
		    	NewsDtos tmpDto=NewsCache.getRecentNews(newsType);
		    	if(tmpDto!=null){
		    		mAdapter.setDatas(tmpDto.data);
			      	mAdapter.notifyDataSetChanged();
		    	}
		    }
		}
		else
			mXListView.hideloading();
	}
	
	public void onClickCollect(final int newsId,final boolean isAdd) {
		// TODO Auto-generated method stub
 		if(AppSetting.curUser==null){
 			 Intent it = new Intent(News_tablist_Fragment.this.mactivity, User_phone_login.class);
 			 it.putExtra("forResult", true);
			 this.startActivityForResult(it, 100);
		    return;
		}
 		/*if(null==mCollectionHelper) mCollectionHelper=new CollectionHelper(this.mactivity);
 		mCollectionHelper.onClickCollect(newsId, isAdd,true);*/
  	}
 	
	/* ��ʼ��֪ͨ��Ŀ*/
	private void initNotify(final int nums,final String errmsg) {
		mhandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				 if(TextUtils.isEmpty(errmsg))
				   notify_view_text.setText(String.format(getString(currentPage==1 ? R.string.ss_pattern_update
								                                           : R.string.ss_pattern_loadmore), nums));
				 else
					 notify_view_text.setText(errmsg);
				notify_view.setVisibility(View.VISIBLE);
				mhandler.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						notify_view.setVisibility(View.GONE);
					}
				}, 2000);
			}
		}, 1000);
	}

	
	
}
